package com.deimos.dataBase;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import org.apache.axiom.om.OMElement;
import org.vast.ows.OWSException;

public class Sensor {

    // public static String sensor_file = System.getProperty("wtp.deploy") +
    // "/HMA-SPS/WEB-INF/services/HMA/Sensors";
    public String sensor_file;
    private static String sensor_dir = getSensorDir();
    // public String sensor_file = ("./src/Sensors");
    public long max_expiration;
    public String id;
    public long study_delay;
    public String[] modes;
    public String[] swaths;
    public String osf_file;
    public String stations_file;
    public String describeTasking;
    public String descriptionFile;
    public double chance;
    public String type;
    public static String OPT = "OPT";
    public static String SAR = "SAR";
    private List<Unavailability> unavailabilities = new ArrayList<Unavailability>();
    public String platformId;
    public String platformName;
    public String instrumentName;
    public String instrumentId;
    private List<String> stations;

    /**
     * @return the type
     */
    public String getType() {
	return type;
    }

    /**
     * @param type
     *            the type to set
     */
    public void setType(String type) {
	this.type = type;
    }

    public void addUnavailability(Unavailability unavailability) {
	unavailabilities.add(unavailability);
    }

    public List<Unavailability> getUnavailabilities() {
	return unavailabilities;
    }

    public long getMax_expiration() {
	return max_expiration;
    }

    public String getDescribeTasking() {
	return describeTasking;
    }

    public void setSensorId(String id) {
	this.id = id;
    }

    public String getSensorId() {
	return id;
    }

    public String getOsf_file() {
	return osf_file;
    }

    public long getStudy_delay() {
	return study_delay;
    }

    public double getChance() {
	return chance;
    }

    public void setChance(double chance) {
	this.chance = chance;
    }
    
    

    /**
     * @return the stations
     */
    public List<String> getStations() {
        return stations;
    }


    public String getSwaths(String mode) {
	if (swaths.length != modes.length || mode == null || mode.isEmpty())
	    return null;
	for (int i = 0; i < modes.length; i++) {
	    if (modes[i].compareTo(mode) == 0) {
		return swaths[i];
	    }
	}
	return null;
    }

    public boolean isSyn() {
	return (study_delay == 0);
    }

    public Sensor() {

    }

    public Sensor(String id) throws OWSException {
	FileInputStream file = null;
	if (id == null)
	    throw new OWSException(OWSException.missing_param_code, "procedure");
	try {

	    Properties properties = new Properties();
	    sensor_file = findSensor(id);
	    file = new FileInputStream(sensor_file + "/configuration");
	    properties.load(file);

	    this.id = properties.getProperty("ID");
	    platformId = properties.getProperty("PLATFORM_ID");
	    platformName = properties.getProperty("PLATFORM_NAME");
	    instrumentName = properties.getProperty("INSTRUMENT_NAME");
	    instrumentId = properties.getProperty("INSTRUMENT_ID");
	    stations = new ArrayList<String>();
	    if (properties.getProperty("STATIONS") != null)
	    for (String station : properties.getProperty("STATIONS").split(",")){
		stations.add(station.replaceAll(" ", ""));
	    }
	    type = properties.getProperty("TYPE");
	    study_delay = Long.parseLong(properties.getProperty("STUDY_DELAY")) * 1000;
	    max_expiration = Long.parseLong(properties.getProperty("MAX_EXPIRATION")) * 60 * 60 * 1000;
	    modes = properties.getProperty("MODE").split(":");
	    chance = Double.parseDouble(properties.getProperty("CHANCE"));
	    osf_file = sensor_file + "/" + properties.getProperty("OSF_FILE");
	    describeTasking = "file:" + sensor_file + "/" + properties.getProperty("DESCRIBE_TASKING");
	    descriptionFile = sensor_file + "/" + properties.getProperty("DESCRIPTION");
	    swaths = new String[modes.length];
	    for (int i = 0; i < modes.length; i++) {
		swaths[i] = (sensor_file + properties.getProperty("SWATH_FILE_" + modes[i]));
	    }

	    file.close();
	} catch (Exception e) {
	    try {
		file.close();
	    } catch (Exception ex) {
	    }
	    // e.printStackTrace();
	    throw new OWSException(OWSException.invalid_param_code, "procedure", "Sensor " + id + " can not be loaded");
	}
    }

    @SuppressWarnings("unchecked")
    public static String getSensor(OMElement request) {
	Iterator iter = request.getChildElements();
	while (iter.hasNext()) {
	    OMElement element = (OMElement) iter.next();
	    if (element.getLocalName().toLowerCase().compareTo("procedure") == 0)
		return element.getText();
	}
	return null;
    }

    public String toString(String token) {
	String text = "";
	text = token + "<Sensor>\n";
	text = text + token + "\t<SensorId>" + id + "</SensorId>\n";
	for (Unavailability unavailability : unavailabilities) {
	    text = text + unavailability.toString(token + "\t") + "\n";
	}
	text = text + token + "</Sensor>";
	return text;
    }

    public String findSensor(String sensorId) {
	String path = null;
	sensorId = sensorId.replaceAll("\n", "");
	sensorId = sensorId.replaceAll("\t", "");
	FileInputStream filei = null;
	try {
	    File file = new File(sensor_dir);
	    for (File subFile : file.listFiles()) {
		if (subFile.isDirectory()) {
		    Properties properties = new Properties();
		    try {
			filei = new FileInputStream(subFile.getPath() + "/configuration");
			properties.load(filei);
			
			if (sensorId.compareTo(properties.getProperty("ID")) == 0){
			    filei.close();
			    return subFile.getPath();
			}			
		    } catch (Exception e) {
		    } finally{
			try {
			    filei.close();
			} catch (Exception e) {
			}
		    }
		}
	    }
	} catch (Exception ex) {

	}
	return path;
    }

    public static List<Sensor> getAllSensor() {
	List<Sensor> sensors = new ArrayList<Sensor>();
	File dir = new File(Sensor.sensor_dir);
	Properties properties = new Properties();
	FileInputStream filei = null;
	for (File file : dir.listFiles()) {
	    try {
		filei = new FileInputStream(file.getPath() + "/configuration");
		properties.load(filei);
		sensors.add(new Sensor(properties.getProperty("ID")));
		filei.close();
	    } catch (Exception e) {
	    } finally {
		try {
		    filei.close();
		} catch (Exception e) {
		}
	    }

	}
	return sensors;
    }

    public static String readDescription(String id) throws OWSException {
	String desc = "";
	int ch;
	StringBuffer strContent = new StringBuffer("");
	FileInputStream file = null;
	try {
	    Sensor sensor = new Sensor(id);
	    file = new FileInputStream(sensor.descriptionFile);
	    while ((ch = file.read()) != -1)
		strContent.append((char) ch);
	    file.close();
	    desc = strContent.toString();
	} catch (Exception e) {
	    if (e instanceof OWSException)
		throw (OWSException) e;
	} finally{
	    try {
		file.close();
	    } catch (Exception ex) {
	    }
	}
	return desc;
    }

    private static String getSensorDir() {
	File file = new File(Cloud.class.getResource("Sensor.class").getPath().toString());
	return (file.getParent() + "/../../../Sensors").replace("file:", "");
    }

}
